package com.yiren.backstage.judge.services.sczb.impl;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.enums.DetourCheckTypeEnum;
import com.yiren.backstage.config.enums.SczbEndConditionEnum;
import com.yiren.backstage.config.enums.SiteConfigCodeEnum;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.VoiceBean;
import com.yiren.backstage.currency.constant.AutoJudgeConstant;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.GradeStandardEntity;
import com.yiren.backstage.currency.entity.ProjectEntity;
import com.yiren.backstage.currency.enums.CarStateValueEnum;
import com.yiren.backstage.currency.enums.ResultStateEnum;
import com.yiren.backstage.currency.enums.TaskStateEnum;
import com.yiren.backstage.currency.utils.MessageUtil;
import com.yiren.backstage.db.dao.cache.GradeStandardCache;
import com.yiren.backstage.currency.bean.SczbStartVoiceBean;
import com.yiren.backstage.judge.handler.AutoJudgeHandler;
import com.yiren.backstage.judge.services.sczb.ICheckDetourService;
import com.yiren.backstage.judge.services.sczb.IPlayOperationVoiceService;
import com.yiren.backstage.judge.services.sczb.ISczbJudgeThreadService;
import com.yiren.backstage.player.api.IPlayerCallBack;
import com.yiren.backstage.player.api.PlayerApi;

import java.util.List;

/**
 * Time:2022/4/7 15:43
 * Author:xiaozan
 * Description：上车准备评判线程服务接口实现
 */
public class SczbJudgeThreadServiceImpl implements ISczbJudgeThreadService {

    private Context context;

    private AutoJudgeHandler autoJudgeHandler;

    private ProjectEntity projectEntity;

    private CarStateBean carState;

    /*** 身份验证语音播报集合 */
    private List<SczbStartVoiceBean> sczbStartVoices;

    private ICheckDetourService iCheckDetourService;

    private IPlayOperationVoiceService iPlayOperationVoiceService;

    /*** 保存绕车执行结果 */
    private ResultStateEnum detourExecuteResult = ResultStateEnum.EXECUTING;

    /*** 保存三摸执行结果 */
    private ResultStateEnum threeAdjustmentExecuteResult = ResultStateEnum.EXECUTING;

    /*** 是否正在播报 */
    private boolean isPlay;

    public SczbJudgeThreadServiceImpl(Context context, AutoJudgeHandler autoJudgeHandler, ProjectEntity projectEntity) {
        this.context = context;
        this.autoJudgeHandler = autoJudgeHandler;
        this.projectEntity = projectEntity;
        this.sczbStartVoices = new Gson().fromJson((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S4.toString()), new TypeToken<List<SczbStartVoiceBean>>() {
        }.getType());
        carState = CarStateBean.getInstance();
        iCheckDetourService = new CheckDetourServiceImpl();
        iPlayOperationVoiceService = new PlayOperationVoiceServiceImpl(context);
    }

    @Override
    public boolean tipsPlayCloseEngine() {
        try {
            if ((boolean) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S1.toString()) && carState.getRotateSpeed() > 200) {
                if ("".equals((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S2.toString())))
                    return true;
                isPlay = true;
                PlayerApi.playProjectAndJudgeVoice(context, new VoiceBean((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S2.toString()), ""), new IPlayerCallBack() {
                    @Override
                    public void playFinish() {
                        isPlay = false;
                    }
                });
                //等待播报完成
                while (isPlay && autoJudgeHandler.getTaskStateEnum() != TaskStateEnum.FORCT_CLOSE) {
                    Thread.sleep(100);
                }

                //休眠时间
                int i = 0;
                int count = (int) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S3.toString()) * 1000 / 100;
                while (autoJudgeHandler.getTaskStateEnum() != TaskStateEnum.FORCT_CLOSE && i <= count) {
                    Thread.sleep(100);
                    i++;
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean playAuthenticationVoice() {
        try {
            //返回播报完成
            if (null == sczbStartVoices || sczbStartVoices.size() == 0) {
                return false;
            }

            VoiceBean voiceBean = new VoiceBean(sczbStartVoices.get(0).getContent(), "");
            isPlay = true;
            PlayerApi.playProjectAndJudgeVoice(context, voiceBean, () -> {
                isPlay = false;
            });
            //等待播报完成
            while (isPlay && autoJudgeHandler.getTaskStateEnum() != TaskStateEnum.FORCT_CLOSE) {
                Thread.sleep(100);
            }

            //休眠时间
            int i = 0;
            int count = (int) ((sczbStartVoices.get(0).getKeepTime() * 1000) / 100);
            while (autoJudgeHandler.getTaskStateEnum() != TaskStateEnum.FORCT_CLOSE && i <= count) {
                Thread.sleep(100);
                i++;
            }
            //播报完成移除
            if (sczbStartVoices.size() > 0) sczbStartVoices.remove(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public boolean executeJudge() {
        try {
            //绕车检测 只在状态是：执行中 执行
            if (detourExecuteResult == ResultStateEnum.EXECUTING) {
                switch (DetourCheckTypeEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S5.toString()))) {
                    case TWO_BUTTON:  //两按钮
                        detourExecuteResult = iCheckDetourService.twoDetour();
                        break;
                    case FOUR_BUTTON:  //四按钮
                        detourExecuteResult = iCheckDetourService.fourDetour();
                        break;
                }
                //执行失败扣分
                if (detourExecuteResult == ResultStateEnum.FAIL)
                    autoJudgeHandler.sendMessage(MessageUtil.newMessage(AutoJudgeConstant.ADD_PROJECT_GRADE, detourGradeStandard()));
            }

            //三摸检测
            if (threeAdjustmentExecuteResult == ResultStateEnum.EXECUTING) {
                if ((boolean) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S12.toString())) {
                    threeAdjustmentExecuteResult = iCheckDetourService.threeAdjustment();
                }
            }

            //结束条件
            boolean end = false;
            switch (SczbEndConditionEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S6.toString()))) {
                case FASTEN_SEAT_BELT:  //系安全带
                    if (carState.getSafetyBelt() == CarStateValueEnum.HITCH) {
                        end = true;
                    }
                    break;
                case START_ENGINE:  //启动发动机
                    if (carState.getRotateSpeed() > 200) {
                        end = true;
                    }
                    break;
            }
            if (end) {
                //未完成绕车扣分
                if (detourExecuteResult == ResultStateEnum.EXECUTING) {
                    autoJudgeHandler.sendMessage(MessageUtil.newMessage(AutoJudgeConstant.ADD_PROJECT_GRADE, detourGradeStandard()));
                }
                //未完成三摸扣分
                if (detourExecuteResult == ResultStateEnum.EXECUTING && (boolean) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S12.toString())) {
                    autoJudgeHandler.sendMessage(MessageUtil.newMessage(AutoJudgeConstant.ADD_PROJECT_GRADE, threeAdjustmentGradeStandard()));
                }

                //结束项目
                autoJudgeHandler.sendMessage(MessageUtil.newMessage(AutoJudgeConstant.PLAY_PROJECT_END_VOICE, projectEntity));

                //上车准备结束后延时多少秒开始模拟灯光
                int i = 0;
                int count = (int) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S7.toString()) * 1000 / 100;
                while (autoJudgeHandler.getTaskStateEnum() != TaskStateEnum.FORCT_CLOSE && i <= count) {
                    Thread.sleep(100);
                    i++;
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void operationPlayVoice() {
        iPlayOperationVoiceService.playHeadLeft();
        iPlayOperationVoiceService.playHeadRight();
        iPlayOperationVoiceService.playTailLeft();
        iPlayOperationVoiceService.playTailRight();
        iPlayOperationVoiceService.playSeat();
        iPlayOperationVoiceService.playReflectorMirror();
        iPlayOperationVoiceService.playRearviewMirror();
    }

    /**
     * 返回上车准备不绕车一周扣分
     *
     * @return
     */
    private GradeStandardEntity detourGradeStandard() {
        //指定评分
        GradeStandardEntity gradeStandardEntity = GradeStandardCache.getGradeStandard("43");
        gradeStandardEntity.setProjectEntity(projectEntity);
        return gradeStandardEntity;
    }

    /**
     * 返回上车准备不调整座椅扣分
     *
     * @return
     */
    private GradeStandardEntity threeAdjustmentGradeStandard() {
        //指定评分
        GradeStandardEntity gradeStandardEntity = GradeStandardCache.getGradeStandard("55");
        gradeStandardEntity.setProjectEntity(projectEntity);
        return gradeStandardEntity;
    }
}
